<template>
    <div class="update-img"
        v-loading="loading"
        element-loading-text="上传中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <div style="float:left"
            class="img-box"
            v-if="imgUrl">
        <img class="img"
            mode="aspectFit"
            v-show="imgUrl"
            :src="imgUrl?imgRoot+imgUrl:''" />
        <i class="clear-icon"
            @click="clearImg()">×</i>
        </div>
        <div style="float:left"
            class="img-box float-left add-img text-center"
            v-else
            @click.stop = "addPic" ref = "upload">
        <label >+</label>
        <input style="opacity:0;"
                type="file" 
                @change="addImgEvent"
                accept="image/png, image/jpeg, image/jpg" />
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import * as api from "./../api/api";
import { IMG_ROOT, OSS_RUL } from "./../config";
export default {
  props: {
    imgUrl: {
      default: "",
      type: String
    }
  },
  data () {
    return {
      imgRoot: IMG_ROOT,
      loading: false,
      client: '',
      progress: '',
    };
  },
  methods: {
    addPic () {
        let els = this.$refs.upload.querySelectorAll('input[type=file]')
        els[0].click()
        return false
    },
    clearImg () {
      this.$emit("clearImg");
    },
    addImgEvent (event) {
        var vm = this;
        api.fetchOssSign().then(res=>{
            if(res.data.code==200){
                var img1 = event.target.files[0];
                let ext = event.target.value.toLowerCase().split('.').splice(-1);
                let mathFloor = Math.floor(Math.random() * 90) + 10;
                var storeAs = (new Date()).getTime() + '' + mathFloor + '.' + ext;
                var size = img1.size / 1024;
                // if(size>200){
                //     vm.$message({
                //     showClose: true,
                //     type: 'error',
                //     message: '图片大小不能大于200KB'
                //     });
                //     return false;
                // }
                let formData = new FormData(); 
                formData.append('OSSAccessKeyId', res.data.data.OSSAccessKeyId);
                formData.append('policy', res.data.data.policy);
                formData.append('key', 'img/'+storeAs);
                formData.append('success_action_status', '200');
                formData.append('Signature', res.data.data.Signature); 
                formData.append('file', img1); 
                vm.loading = true;
                axios({
                    url: res.data.data.domain,
                    header:{
                    'Content-Type': 'multipart/form-data'
                    },
                    method: 'post',
                    data: formData
                }).then(ossRes => { 
                    vm.loading = false;
                    if(ossRes.status===200){ 
                        console.log(ossRes);
                        vm.dataList = res.data.data.domain+'/img/'+storeAs; 
                        vm.$emit("change", res.data.data.domain+'/img/'+storeAs);
                        //   console.log(res.name);
                        vm.$message({
                            message: '上传成功！',
                            type: 'success'
                        });
                    }
                }).catch(function (err) { 
                    console.log('err',err);
                    vm.loading = false;
                    vm.$message({
                        showClose: true,
                        message: '服务器错误！'
                    })
                })
                event.target.value = ""; 
            }
        }) 
        // // 调用上传方法
        // vm.client.multipartUpload(storeAs, img1, {
        //     // progress: function* (percentage) {
        //     //   let fileloadingNum = Math.ceil(percentage * 100) + '%'
        //     //   vm.progress = fileloadingNum

        //     // }
        // }).then(function (res) {
        //     vm.loading = false;
        //     if (res.res.status == 200) {
        //     // vm.dataList = res.name;
        //     // // setTimeout(()=>{
        //     // //     vm.$emit('change',vm.dataList,vm.audioLength);
        //     // // },1600); 
        //     vm.$emit("change", res.name);
        //     //   console.log(res.name);
        //     vm.$message({
        //         message: '上传成功！',
        //         type: 'success'
        //     });
        //     }
        // }).catch(function (err) {
        //     vm.loading = false;
        //     vm.$message({
        //     showClose: true,
        //     message: '服务器错误！'
        //     })
        // })
        // event.target.value = "";
    }
  }
};
</script>

<style lang="scss" scoped>
.update-img {
  display: inline-block;
  // margin-left: 10px;
  .img-box {
    position: relative;
    display: inline-block;
    height: 160px;
    width: 160px;
    color: #dedede;
    // margin-right: 20px;
    padding: 20px;
    box-sizing: border-box;
    .img {
      height: 100%;
      width: 100%;
    }
    .clear-icon {
      position: absolute;
      top: 8px;
      right: 8px;
      width: 26px;
      height: 26px;
      text-align: center;
      line-height: 26px;
      font-size: 20px;
      border-radius: 50%;
      background: #ec514a;
      color: #fff;
      cursor: pointer;
    }
  }
  .add-img {
    line-height: 110px;
    border: 1px dotted #dedede;
    label {
      font-size: 40px;
      display: inline-block;
      text-align: center;
      width: 100%;
      height: 100%;
    }
    input {
      position: absolute;
      top: 0;
      left: 0;
      width: 0;
      height: 0;
    }
  }
}
</style>
